# 表单验证，验证数据
import wtforms
from wtforms.validators import Email, Length, EqualTo, InputRequired
from models import UserModel, EmailCaptchaModel
from exts import db

# Form 主要就是用来验证前端提交的数据是否符合要求
class RegisterForm (wtforms.Form) :   # 验证注册时候的数据是否合法正确
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误！")])   # validators验证邮箱格式是否正确 Email是验证器
    # StringField表示字符串格式                      message:如果邮箱格式验证失败，所给得提示
    captcha = wtforms.StringField(validators=[Length(min=4, max=4, message="验证码格式错误")])
    # Length:验证长度
    username = wtforms.StringField(validators=[Length(min=3, max=20, message="用户名格式错误")])
    password = wtforms.StringField(validators=[Length(min=6, max=20, message="密码格式错误")])
    password_confirm = wtforms.StringField(validators=[EqualTo("password", message="两次密码不一致")])
    # EqualTo验证和那个字段相等

    # 自定义验证:
    # 1.邮箱是否已经被注册
    def validate_email(self, field):
        email = field.data
        user = UserModel.query.filter_by(email=email).first()
        # filter_by查找 query中的一个用法
        if user:
            raise wtforms.ValidationError(message="该邮箱已经被注册了!")
            # raise抛出异常/异常       ValidationError验证错误

    # 2.验证码是否正确
    def validate_captcha(self, field):
        captcha = field.data
        # 上边两句是固定的写法:现在验证的是captcha，field代表的就是captcha字段，字段上边有个属性叫data，就可以获取到字段上边的值，也就是用户现在输入进来的验证码
        email = self.email.data    # self就代表当前的对象
        captcha_model = EmailCaptchaModel.query.filter_by(email=email, captcha=captcha).first()
        if not captcha_model:
            raise wtforms.ValidationError(message="邮箱或者验证码错误!")
        # else:
        #     db.session.delete(captcha_model)
        #     db.session.commit()


class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[Email(message="邮箱格式错误！")])   # validators验证邮箱格式是否正确 Email是验证器
    password = wtforms.StringField(validators=[Length(min=6, max=20, message="密码格式错误")])


class QuestionForm(wtforms.Form):
    title = wtforms.StringField(validators=[Length(min=3, max=100, message="标题格式错误")])
    content = wtforms.StringField(validators=[Length(min=3, message="内容格式错误")])

class AnswerForm(wtforms.Form):
    content = wtforms.StringField(validators=[Length(min=3, message="内容格式错误")])
    question_id = wtforms.IntegerField(validators=[InputRequired(message="必须要传入问题id！")])
                                                   # InputRequired验证器  必须要输入
















































